<!DOCTYPE html>




<html class="theme-next mist" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="-参数优化," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="梯度下降(Batch gradient descent)–BGD123456789101112131415161718192021# 梯度下降(Batch gradient descent)--BGDdef batch_gradient_descent(x, y, learn_rate, epoches):    &quot;&quot;&quot;    :param x:  输入的x    :param y:  输入的y">
<meta name="keywords" content="-参数优化">
<meta property="og:type" content="article">
<meta property="og:title" content="BGD、SGD和MBGD的一些区别">
<meta property="og:url" content="http://yoursite.com/2017/09/12/BGD、SGD和MBGD的一些区别/index.html">
<meta property="og:site_name" content="ryanbing">
<meta property="og:description" content="梯度下降(Batch gradient descent)–BGD123456789101112131415161718192021# 梯度下降(Batch gradient descent)--BGDdef batch_gradient_descent(x, y, learn_rate, epoches):    &quot;&quot;&quot;    :param x:  输入的x    :param y:  输入的y">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2017-09-12T00:33:34.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="BGD、SGD和MBGD的一些区别">
<meta name="twitter:description" content="梯度下降(Batch gradient descent)–BGD123456789101112131415161718192021# 梯度下降(Batch gradient descent)--BGDdef batch_gradient_descent(x, y, learn_rate, epoches):    &quot;&quot;&quot;    :param x:  输入的x    :param y:  输入的y">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    sidebar: {"position":"right","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/09/12/BGD、SGD和MBGD的一些区别/"/>





  <title>BGD、SGD和MBGD的一些区别 | ryanbing</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">ryanbing</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/09/12/BGD、SGD和MBGD的一些区别/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ryanbing">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="ryanbing">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">BGD、SGD和MBGD的一些区别</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-09-12T08:16:00+08:00">
                2017-09-12
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">-机器学习</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="梯度下降-Batch-gradient-descent-–BGD"><a href="#梯度下降-Batch-gradient-descent-–BGD" class="headerlink" title="梯度下降(Batch gradient descent)–BGD"></a>梯度下降(Batch gradient descent)–BGD</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 梯度下降(Batch gradient descent)--BGD</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">batch_gradient_descent</span><span class="params">(x, y, learn_rate, epoches)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x:  输入的x</span></div><div class="line"><span class="string">    :param y:  输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        <span class="comment"># 全部的值带入，计算 梯度</span></div><div class="line">        m = len(y)</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(m):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / m</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / m</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line">    <span class="keyword">return</span> theta</div></pre></td></tr></table></figure>
<h3 id="随机梯度下降-Stochastic-gradient-descent-–SGD"><a href="#随机梯度下降-Stochastic-gradient-descent-–SGD" class="headerlink" title="随机梯度下降(Stochastic gradient descent)–SGD"></a>随机梯度下降(Stochastic gradient descent)–SGD</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># 这不是随机梯度，随机梯度是每迭代一次，数据就随机一次---但是这也是一种处理手段</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stochastic_gradient_descent_false</span><span class="params">(x, y, learn_rate, epoches, stochastic_rate)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    shufflle_data = np.column_stack((y, x))</div><div class="line">    np.random.shuffle(shufflle_data)</div><div class="line">    stochastic_count = int(len(y) * stochastic_rate)</div><div class="line">    <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">    y = shufflle_data[:stochastic_count, <span class="number">0</span>]</div><div class="line">    x = shufflle_data[:stochastic_count, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line">    <span class="keyword">return</span> batch_gradient_descent(x, y, learn_rate, epoches)</div><div class="line"><span class="comment"># 正确的随机梯度应该是这样</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stochastic_gradient_descent_true</span><span class="params">(x, y, learn_rate, epoches, stochastic_rate)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        shufflle_data = np.column_stack((y, x))</div><div class="line">        np.random.shuffle(shufflle_data)</div><div class="line">        stochastic_count = int(len(y) * stochastic_rate)</div><div class="line">        <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">        y = shufflle_data[:stochastic_count, <span class="number">0</span>]</div><div class="line">        x = shufflle_data[:stochastic_count, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line">        <span class="comment"># 随机之后的值，进行梯度计算</span></div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        m = len(y)</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(m):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / m</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / m</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line">    <span class="keyword">return</span> theta</div></pre></td></tr></table></figure>
<h3 id="小批量梯度下降-Mini-batch-gradient-descent-–MBGD"><a href="#小批量梯度下降-Mini-batch-gradient-descent-–MBGD" class="headerlink" title="小批量梯度下降(Mini-batch gradient descent)–MBGD"></a>小批量梯度下降(Mini-batch gradient descent)–MBGD</h3><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div></pre></td><td class="code"><pre><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">mini_batch_gradient_descent</span><span class="params">(x, y, learn_rate, epoches, mini_length)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :param mini_length: mini batch length</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    <span class="comment"># 随机打乱----optional</span></div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="comment"># 随机打乱数据  ----optional</span></div><div class="line">    shufflle_data = np.column_stack((y, x))</div><div class="line">    np.random.shuffle(shufflle_data)</div><div class="line">    <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">    y = shufflle_data[:, <span class="number">0</span>]</div><div class="line">    x = shufflle_data[:, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line"></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        <span class="comment"># 0-min_length， mini_length+1  2mini_length, ....... 一小段，一小段距离用于一次优化迭代</span></div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">0</span>, len(y), mini_length):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / mini_length</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / mini_length</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line"></div><div class="line">    <span class="keyword">return</span> theta</div></pre></td></tr></table></figure>
<h4 id="实验代码"><a href="#实验代码" class="headerlink" title="实验代码"></a>实验代码</h4><figure class="highlight python"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div><div class="line">64</div><div class="line">65</div><div class="line">66</div><div class="line">67</div><div class="line">68</div><div class="line">69</div><div class="line">70</div><div class="line">71</div><div class="line">72</div><div class="line">73</div><div class="line">74</div><div class="line">75</div><div class="line">76</div><div class="line">77</div><div class="line">78</div><div class="line">79</div><div class="line">80</div><div class="line">81</div><div class="line">82</div><div class="line">83</div><div class="line">84</div><div class="line">85</div><div class="line">86</div><div class="line">87</div><div class="line">88</div><div class="line">89</div><div class="line">90</div><div class="line">91</div><div class="line">92</div><div class="line">93</div><div class="line">94</div><div class="line">95</div><div class="line">96</div><div class="line">97</div><div class="line">98</div><div class="line">99</div><div class="line">100</div><div class="line">101</div><div class="line">102</div><div class="line">103</div><div class="line">104</div><div class="line">105</div><div class="line">106</div><div class="line">107</div><div class="line">108</div><div class="line">109</div><div class="line">110</div><div class="line">111</div><div class="line">112</div><div class="line">113</div><div class="line">114</div><div class="line">115</div><div class="line">116</div><div class="line">117</div><div class="line">118</div><div class="line">119</div><div class="line">120</div><div class="line">121</div><div class="line">122</div><div class="line">123</div><div class="line">124</div><div class="line">125</div><div class="line">126</div><div class="line">127</div><div class="line">128</div><div class="line">129</div><div class="line">130</div><div class="line">131</div><div class="line">132</div><div class="line">133</div><div class="line">134</div><div class="line">135</div><div class="line">136</div><div class="line">137</div><div class="line">138</div><div class="line">139</div><div class="line">140</div><div class="line">141</div><div class="line">142</div><div class="line">143</div><div class="line">144</div><div class="line">145</div><div class="line">146</div><div class="line">147</div><div class="line">148</div><div class="line">149</div><div class="line">150</div><div class="line">151</div><div class="line">152</div><div class="line">153</div><div class="line">154</div><div class="line">155</div><div class="line">156</div><div class="line">157</div><div class="line">158</div><div class="line">159</div><div class="line">160</div><div class="line">161</div><div class="line">162</div><div class="line">163</div><div class="line">164</div><div class="line">165</div><div class="line">166</div><div class="line">167</div><div class="line">168</div><div class="line">169</div><div class="line">170</div><div class="line">171</div><div class="line">172</div><div class="line">173</div><div class="line">174</div><div class="line">175</div><div class="line">176</div><div class="line">177</div><div class="line">178</div><div class="line">179</div><div class="line">180</div><div class="line">181</div><div class="line">182</div><div class="line">183</div><div class="line">184</div><div class="line">185</div><div class="line">186</div><div class="line">187</div><div class="line">188</div><div class="line">189</div><div class="line">190</div><div class="line">191</div><div class="line">192</div><div class="line">193</div><div class="line">194</div><div class="line">195</div><div class="line">196</div><div class="line">197</div><div class="line">198</div><div class="line">199</div></pre></td><td class="code"><pre><div class="line"><span class="comment"># -*- coding: utf-8 -*-</span></div><div class="line"><span class="comment"># @Date    : 2017/9/8</span></div><div class="line"><span class="comment"># @Author  : ryanbing (legotime@qq.com)</span></div><div class="line"></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> matplotlib.pyplot <span class="keyword">as</span> plt</div><div class="line"><span class="keyword">import</span> datetime</div><div class="line"></div><div class="line">rng = np.random.RandomState(<span class="number">1</span>)</div><div class="line">x = <span class="number">10</span> * rng.rand(<span class="number">500</span>)</div><div class="line">y = <span class="number">3</span> * x + <span class="number">2</span> + rng.randn(<span class="number">500</span>)</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># plt.scatter(x, y)</span></div><div class="line"><span class="comment"># plt.show()</span></div><div class="line"></div><div class="line"><span class="comment"># 找出 y = wx + b 中的w 和 b, 正确的应该是 w = 3, b = 2</span></div><div class="line"><span class="comment"># 我们在计算的时候其看成 y = WX 其中 W= [w, b], X = [x, 1].T</span></div><div class="line"></div><div class="line"><span class="comment"># 梯度下降(Batch gradient descent)--BGD</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">batch_gradient_descent</span><span class="params">(x, y, learn_rate, epoches)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x:  输入的x</span></div><div class="line"><span class="string">    :param y:  输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    start_time = datetime.datetime.now()</div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        <span class="comment"># 全部的值带入，计算 梯度</span></div><div class="line">        m = len(y)</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(m):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / m</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / m</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line">    end_time = datetime.datetime.now()</div><div class="line">    <span class="keyword">return</span> end_time - start_time, theta</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># 这不是随机梯度，随机梯度是每迭代一次，数据就随机一次---但是这也是一种处理手段</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stochastic_gradient_descent_false</span><span class="params">(x, y, learn_rate, epoches, stochastic_rate)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    start_time = datetime.datetime.now()</div><div class="line">    shufflle_data = np.column_stack((y, x))</div><div class="line">    np.random.shuffle(shufflle_data)</div><div class="line">    stochastic_count = int(len(y) * stochastic_rate)</div><div class="line">    <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">    y = shufflle_data[:stochastic_count, <span class="number">0</span>]</div><div class="line">    x = shufflle_data[:stochastic_count, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line">    end_time = datetime.datetime.now()</div><div class="line">    <span class="keyword">return</span> end_time - start_time, batch_gradient_descent(x, y, learn_rate, epoches)</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># 正确的随机梯度应该是这样</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">stochastic_gradient_descent_true</span><span class="params">(x, y, learn_rate, epoches, stochastic_rate)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    start_time = datetime.datetime.now()</div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        shufflle_data = np.column_stack((y, x))</div><div class="line">        np.random.shuffle(shufflle_data)</div><div class="line">        stochastic_count = int(len(y) * stochastic_rate)</div><div class="line">        <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">        y = shufflle_data[:stochastic_count, <span class="number">0</span>]</div><div class="line">        x = shufflle_data[:stochastic_count, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line">        <span class="comment"># 随机之后的值，进行梯度计算</span></div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        m = len(y)</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(m):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / m</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / m</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line">    end_time = datetime.datetime.now()</div><div class="line"></div><div class="line">    <span class="keyword">return</span> end_time - start_time, theta</div><div class="line"></div><div class="line"></div><div class="line"><span class="comment"># 小批量梯度下降(Mini-batch gradient descent)--MBGD</span></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">mini_batch_gradient_descent</span><span class="params">(x, y, learn_rate, epoches, mini_length)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param x: 输入的x</span></div><div class="line"><span class="string">    :param y: 输入的y</span></div><div class="line"><span class="string">    :param learn_rate: 学习率</span></div><div class="line"><span class="string">    :param epoches: 迭代次数</span></div><div class="line"><span class="string">    :param mini_length: mini batch length</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line">    start_time = datetime.datetime.now()</div><div class="line">    <span class="comment"># 随机打乱----optional</span></div><div class="line">    theta = np.array([<span class="number">0.0</span>, <span class="number">0.0</span>])</div><div class="line">    <span class="comment"># 随机打乱数据  ----optional</span></div><div class="line">    shufflle_data = np.column_stack((y, x))</div><div class="line">    np.random.shuffle(shufflle_data)</div><div class="line">    <span class="comment"># 然后随机取一些数据进行梯度优化， 比如取随机100条数据</span></div><div class="line">    y = shufflle_data[:, <span class="number">0</span>]</div><div class="line">    x = shufflle_data[:, <span class="number">1</span>:<span class="number">3</span>]</div><div class="line"></div><div class="line">    <span class="keyword">for</span> i <span class="keyword">in</span> range(epoches):</div><div class="line">        <span class="comment"># 0-min_length， mini_length+1  2mini_length, ....... 一小段，一小段距离用于一次优化迭代</span></div><div class="line">        loss = [<span class="number">0.0</span>, <span class="number">0.0</span>]</div><div class="line">        <span class="keyword">for</span> j <span class="keyword">in</span> range(<span class="number">0</span>, len(y), mini_length):</div><div class="line">            loss[<span class="number">0</span>] = loss[<span class="number">0</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) * x[j, <span class="number">0</span>] / mini_length</div><div class="line">            loss[<span class="number">1</span>] = loss[<span class="number">1</span>] + (theta[<span class="number">0</span>] * x[j, <span class="number">0</span>] + theta[<span class="number">1</span>] * x[j, <span class="number">1</span>] - y[j]) / mini_length</div><div class="line">        <span class="comment"># 更新 theta</span></div><div class="line">        theta[<span class="number">0</span>] = theta[<span class="number">0</span>] - learn_rate * loss[<span class="number">0</span>]</div><div class="line">        theta[<span class="number">1</span>] = theta[<span class="number">1</span>] - learn_rate * loss[<span class="number">1</span>]</div><div class="line">    end_time = datetime.datetime.now()</div><div class="line"></div><div class="line">    <span class="keyword">return</span> end_time - start_time, theta</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">contro_func</span><span class="params">(func, **kwargs)</span>:</span></div><div class="line">    <span class="string">"""</span></div><div class="line"><span class="string">    :param func: 函数</span></div><div class="line"><span class="string">    :param kwargs:  func 中需要的参数</span></div><div class="line"><span class="string">    :return:</span></div><div class="line"><span class="string">    """</span></div><div class="line"></div><div class="line">    x = kwargs.get(<span class="string">'x'</span>, <span class="keyword">None</span>)</div><div class="line">    y = kwargs.get(<span class="string">'y'</span>, <span class="keyword">None</span>)</div><div class="line">    learn_rate = kwargs.get(<span class="string">'learn_rate'</span>, <span class="keyword">None</span>)</div><div class="line">    epoches = kwargs.get(<span class="string">'epoches'</span>, <span class="keyword">None</span>)</div><div class="line">    stochastic_rate = kwargs.get(<span class="string">'stochastic_rate'</span>, <span class="keyword">None</span>)</div><div class="line">    mini_length = kwargs.get(<span class="string">'mini_length'</span>, <span class="keyword">None</span>)</div><div class="line"></div><div class="line">    <span class="comment"># change the value is args is not num</span></div><div class="line"></div><div class="line">    <span class="keyword">if</span> stochastic_rate <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</div><div class="line">        <span class="keyword">return</span> func(x, y, learn_rate, epoches, stochastic_rate)</div><div class="line">    <span class="keyword">if</span> mini_length <span class="keyword">is</span> <span class="keyword">not</span> <span class="keyword">None</span>:</div><div class="line">        <span class="keyword">return</span> func(x, y, learn_rate, epoches, mini_length)</div><div class="line">    <span class="keyword">return</span> func(x, y, learn_rate, epoches)</div><div class="line"></div><div class="line"></div><div class="line"><span class="function"><span class="keyword">def</span> <span class="title">show_trend</span><span class="params">()</span>:</span></div><div class="line">    <span class="comment"># 画出收敛的的图像和收敛对应的时间</span></div><div class="line">    rng = np.random.RandomState(<span class="number">1</span>)</div><div class="line">    x = <span class="number">10</span> * rng.rand(<span class="number">500</span>)</div><div class="line">    x = np.array([x, np.ones(<span class="number">500</span>)]).T</div><div class="line">    y = <span class="number">3</span> * x + <span class="number">2</span> + rng.randn(<span class="number">500</span>)</div><div class="line">    learn_rate = <span class="number">0.01</span></div><div class="line">    stochastic_rate = <span class="number">0.4</span></div><div class="line">    mini_length = <span class="number">10</span></div><div class="line"></div><div class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> [batch_gradient_descent, stochastic_gradient_descent_false,</div><div class="line">              stochastic_gradient_descent_true, mini_batch_gradient_descent]:</div><div class="line">        tmp = []</div><div class="line">        <span class="keyword">for</span> epoches <span class="keyword">in</span> [<span class="number">1</span>, <span class="number">10</span>, <span class="number">100</span>, <span class="number">1000</span>, <span class="number">10000</span>, <span class="number">100000</span>]:</div><div class="line">            tmp.append(contro_func(i, x=x, y=y, learn_rate=learn_rate, stochastic_rate=stochastic_rate,</div><div class="line">                                   mini_length=mini_length, epoches=epoches))</div><div class="line"></div><div class="line"></div><div class="line"></div><div class="line"><span class="keyword">if</span> __name__ == <span class="string">'__main__'</span>:</div><div class="line">    <span class="comment"># test(func=func, x=1, y=2, learn_rate=3, epoches=4, stochastic_rate=5)</span></div><div class="line"></div><div class="line">    <span class="comment"># print(batch_gradient_descent(np.array([x, np.ones(500)]).T, y, learn_rate=0.01, epoches=100000))</span></div><div class="line">    <span class="comment"># [ 1.14378512 0.17288215]</span></div><div class="line">    <span class="comment"># [ 3.18801281 0.50870366]</span></div><div class="line">    <span class="comment"># [ 3.18602557 0.806018 ]</span></div><div class="line">    <span class="comment"># [ 3.03276102 1.84267445]</span></div><div class="line">    <span class="comment"># [ 3.01449298 1.96623647]</span></div><div class="line">    <span class="comment"># [ 3.01449298 1.96623647]</span></div><div class="line"></div><div class="line">    <span class="comment"># print(stochastic_gradient_descent_false(np.array([x, np.ones(500)]).T, y, learn_rate=0.01, epoches=100,stochastic_rate=0.4))</span></div><div class="line">    <span class="comment"># [ 1.11939055 0.16949282]</span></div><div class="line">    <span class="comment"># [ 3.19877639 0.50404936]</span></div><div class="line">    <span class="comment"># [ 3.20921332 0.78698163]</span></div><div class="line">    <span class="comment"># [ 3.04720128 1.82412805]</span></div><div class="line">    <span class="comment"># [ 3.01920995 1.89883629]</span></div><div class="line">    <span class="comment"># [ 2.98281143 2.15226071]</span></div><div class="line"></div><div class="line">    <span class="comment"># print(stochastic_gradient_descent_true(np.array([x, np.ones(50000)]).T, y, learn_rate=0.01, epoches=1000,stochastic_rate=1))</span></div><div class="line"></div><div class="line">    <span class="comment"># print(mini_batch_gradient_descent(np.array([x, np.ones(500)]).T, y, learn_rate=0.01, epoches=100, mini_length=10))</span></div><div class="line">    <span class="comment"># [ 0.94630842  0.14845568]</span></div><div class="line">    <span class="comment"># [ 0.8811451   0.15444328]</span></div><div class="line">    <span class="comment"># [ 3.18337012  0.51049921]</span></div><div class="line">    <span class="comment"># [ 3.14833317  0.79174635]</span></div><div class="line">    <span class="comment"># [ 3.03507147  1.87931184]</span></div></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/参数优化/" rel="tag"># -参数优化</a>
          
        </div>
      

      
      
      

      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.png"
               alt="ryanbing" />
          <p class="site-author-name" itemprop="name">ryanbing</p>
           
              <p class="site-description motion-element" itemprop="description">ryanbing's blog</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives/">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">1</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://blog.csdn.net/legotime" target="_blank" title="CSDN">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                    
                      CSDN
                    
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#梯度下降-Batch-gradient-descent-–BGD"><span class="nav-number">1.</span> <span class="nav-text">梯度下降(Batch gradient descent)–BGD</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#随机梯度下降-Stochastic-gradient-descent-–SGD"><span class="nav-number">2.</span> <span class="nav-text">随机梯度下降(Stochastic gradient descent)–SGD</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#小批量梯度下降-Mini-batch-gradient-descent-–MBGD"><span class="nav-number">3.</span> <span class="nav-text">小批量梯度下降(Mini-batch gradient descent)–MBGD</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#实验代码"><span class="nav-number">3.1.</span> <span class="nav-text">实验代码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2017</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ryanbing</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Mist
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/three/three.min.js"></script>

  
  <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
